package supervise

import (
	"fmt"
	"io"
	"net/http"

	"admin.supervise.limaochuxing.top/config"
	"admin.supervise.limaochuxing.top/core"
	"admin.supervise.limaochuxing.top/middleware"

	"github.com/gin-gonic/gin"
)

var SuperviseGroup = core.Group("/supervise", newSuperviseHandler, regSupervise, middleware.TokenAuth())

func newSuperviseHandler() *superviseHandler {
    return &superviseHandler{}
}

func regSupervise(rg *gin.RouterGroup, group *core.GroupBase) error {
    return group.Reg(func(handle *superviseHandler) {
        rg.Any("/*path", func(c *gin.Context) {
            // 直接转发请求
            targetURL := config.Config.SuperviseTargetUrl + c.Param("path")
            // 如果是 GET 请求，需要添加查询参数
            if c.Request.Method == "GET" {
                queryParams := c.Request.URL.Query().Encode()
                if queryParams != "" {
                    targetURL = fmt.Sprintf("%s?%s", targetURL, queryParams)
                }
            }

            
            // 创建新的请求
            req, _ := http.NewRequest(c.Request.Method, targetURL, c.Request.Body)
            
            // 复制原始请求的header
            for k, v := range c.Request.Header {
                req.Header[k] = v
            }
            // 发送请求
            client := &http.Client{}
            resp, err := client.Do(req)
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
                return
            }
            defer resp.Body.Close()
            
            // 复制响应header
            for k, v := range resp.Header {
                c.Writer.Header()[k] = v
            }
            // 设置状态码
            c.Writer.WriteHeader(resp.StatusCode)
            
            // 复制响应body
            _, _ = io.Copy(c.Writer, resp.Body)
        })
    })
}

type superviseHandler struct{}

type noAuthSuperviseHandler struct{}

func newNoAuthSuperviseHandler() *noAuthSuperviseHandler {
    return &noAuthSuperviseHandler{}
}

var NoAuthSuperviseGroup = core.Group("/no-auth/supervise", newNoAuthSuperviseHandler, regNoAuthSupervise)

func regNoAuthSupervise(rg *gin.RouterGroup, group *core.GroupBase) error {
    return group.Reg(func(handle *noAuthSuperviseHandler) {
        rg.Any("/*path", func(c *gin.Context) {
            // 直接转发请求
            targetURL := config.Config.SuperviseTargetUrl + c.Param("path")
            // 如果是 GET 请求，需要添加查询参数
            if c.Request.Method == "GET" {
                queryParams := c.Request.URL.Query().Encode()
                if queryParams != "" {
                    targetURL = fmt.Sprintf("%s?%s", targetURL, queryParams)
                }
            }

            
            // 创建新的请求
            req, _ := http.NewRequest(c.Request.Method, targetURL, c.Request.Body)
            
            // 复制原始请求的header
            for k, v := range c.Request.Header {
                req.Header[k] = v
            }
            // 发送请求
            client := &http.Client{}
            resp, err := client.Do(req)
            if err != nil {
                c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
                return
            }
            defer resp.Body.Close()
            
            // 复制响应header
            for k, v := range resp.Header {
                c.Writer.Header()[k] = v
            }
            // 设置状态码
            c.Writer.WriteHeader(resp.StatusCode)
            
            // 复制响应body
            _, _ = io.Copy(c.Writer, resp.Body)
        })
    }) 
}